#include "QtCommonComponet.h"
#include <QDebug>
#include <QMessageBox>
#include <QJsonValue>
#include <QJsonObject>

#include "ScreenWidget/screenwidget.h"


#define CONTROL_LAMP_NG "min-width: 28px; min-height: 28px;max-width:28px; max-height: 28px;border-radius: 14px;  border:0px solid black;background:red"
#define CONTROL_LAMP_OK "min-width: 28px; min-height: 28px;max-width:28px; max-height: 28px;border-radius: 14px;  border:0px solid black;background:green"


QtCommonComponet::QtCommonComponet(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::QtCommonComponetClass())
{
    ui->setupUi(this);

    qDebug() << "ssssssssssweeeee";

    InitVerifyCodeWidget();
    initDB();
    initMysqlDB();
    initHttpServer();
    //initHttpClient();
    initComSerialPort();
    initMultiThreadFramework();

    //initTCPServer();
    // 验证码
    connect(ui->pushButton_verifyCode, &QPushButton::clicked, this, &QtCommonComponet::slot_pushButtonVerfyCode);
    // 截图
    connect(ui->pushButton_screen, &QPushButton::clicked, this, [this]() {
        ScreenWidget::Instance()->showFullScreen();
        });
    // 串口
    connect(ui->comboBox_SerialPortItems, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &QtCommonComponet::slot_comportIndexChanged);
    // 提示弹窗
    connect(ui->pushButton_Info, &QPushButton::clicked, this, &QtCommonComponet::slot_showMessageBox);
    // materialDesign使用
    ui->pushButton_Info->setIcon(QIcon(material::pixmap("folder-cancel-outline", QSize(20, 20), QColor("#333333"))));

    // 提示音
    connect(ui->pushButton_sound, &QPushButton::clicked, this, &QtCommonComponet::slot_soundPlay);


    // 打印机
    m_pTagPrintControl = new TagPrintControl(NULL);
    QStringList printDevices = m_pTagPrintControl->GetTagPrintInstall();
    bool search_pre_print_device = false;
    for (auto& device : printDevices)
    {
        if (!device.contains("ZPL")) continue;

        ui->comboBox_printInfo->addItem(device.trimmed());
    }
    connect(ui->pushButton_print, &QPushButton::clicked, this, &QtCommonComponet::slot_printTag);
}

QtCommonComponet::~QtCommonComponet()
{
    ScreenWidget::Instance()->deleteLater();
    xxManager::globalInstance().shutdown();

    if (m_binaryClient) {
        // 断开所有信号槽
        m_binaryClient->disconnect();
        // 强制释放资源
        m_binaryClient.clear();
    }

    delete ui;
}

/// <summary>
/// 图形验证码
/// </summary>
void QtCommonComponet::InitVerifyCodeWidget()
{

    verifyCodeWidget = new VerifyCodeWidget(this);
    verifyCodeWidget->setStyleSheet("VerifyCodeWidget {background-color: white;} VerifyCodeWidget:hover {background-color: lightGray;}");

    //ui->widget_verifyCode = verifyCodeWidget;
    ui->gridLayout->addWidget(verifyCodeWidget, 0, 0, 1, 2);
    ui->gridLayout->addWidget(ui->lineEdit_verifyCode, 1, 0);
    ui->gridLayout->addWidget(ui->pushButton_verifyCode, 1, 1);
}
void QtCommonComponet::slot_pushButtonVerfyCode() {
    QString code = ui->lineEdit_verifyCode->text();
    if (verifyCodeWidget->checkVerifyCode(code)) {
        QMessageBox::information(this, "提示", "验证码正确");
    }
    else {
        QMessageBox::warning(this, "提示", "验证码错误");
    }
}

/// <summary>
/// sqlite数据库使用
/// </summary>
void QtCommonComponet::initDB()
{
    m_data_db = QSharedPointer<BaseSqliteHelper>::create();
    m_data_db->createCheckDB("testDB");

    QSharedPointer<BasicDetectionDefine> data = QSharedPointer<BasicDetectionDefine>::create();
    data->barcode = "sasdad";
    data->date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    data->upload = 1;

    //m_data_db->insertData(data);
    //m_data_db->updateData(data);
    data = m_data_db->getNewestData("sasdad");
    qDebug() << data->barcode;
}

/// <summary>
/// mysql数据库使用
/// </summary>
void QtCommonComponet::initMysqlDB()
{
    // 初始化
    ConnInfo_Db  db;
    db.dbName = "mes_test";
    db.password = "123456";
    db.port = 3306;
    db.serverName = "127.0.0.1";
    db.userName = "root";
    ConnMySqHelper::initDbPool(db);  // 初始化mysql，进行连接
    // 创建表
    m_mysqlData_db->createBcweldingDB();
    // 插入数据
    QSharedPointer<BasicDetectionDefine2> Data = QSharedPointer<BasicDetectionDefine2>::create();
    Data->barcode = "asdada";
    Data->date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    Data->message = "test is a";
    Data->uid = QUuid::createUuid().toString();
    Data->upload = 0;
    m_mysqlData_db->insertData(Data);
}

/// <summary>
/// Http模块测试
/// </summary>
void QtCommonComponet::initHttpClient()
{
    m_httpClient = QSharedPointer<QNetworkHttpClient>::create("127.0.0.1", 8080);

    if (m_httpClient) {
        // get 异步请求
        //QSharedPointer<ResponseContent> rsp = m_httpClient->getJsonASyncNonblocking("/getA", 3000, 1);
        // get带参
        //QSharedPointer<ResponseContent> rsp = m_httpClient->getJsonASyncNonblocking("/api/code/getId?BatchId=1254", 3000, 1);
        //// get同步请求
        //QSharedPointer<ResponseContent> rsp = m_httpClient->getJsonSync("/getA", 3000, 1);
        //
        //// post请求
        QJsonObject json;
        json["test"] = "test";
        QString jsonStr = QJsonDocument(json).toJson(QJsonDocument::Compact);
        //// post异步请求
        //QSharedPointer<ResponseContent> rsp = m_httpClient->postJsonASyncNonblocking("/getA", jsonStr, 3000, 1);
        //// post同步请求
        QSharedPointer<ResponseContent> rsp = m_httpClient->postJsonSync("/getA", jsonStr, 3000, 1);


        // 处理响应 get post一样处理
        if (rsp != nullptr) {
            if (200 == rsp->StatusCode) {
                QJsonParseError error;
                const QJsonDocument& document = QJsonDocument::fromJson(rsp->BodyContent.toUtf8(), &error);
                if (QJsonParseError::NoError == error.error) {
                    const QJsonObject& programmerObject = document.object();
                    QString test = programmerObject.value("test").toString();
                }
            }
            else {
                qDebug() << QString("%1请求异常");
            }
        }
    }
}
void QtCommonComponet::initHttpServer()
{
    m_httpServer = std::make_shared<QNetworkHttpServer>(this);
    m_httpServer->getJsonApi("/api/login", [&](const SimpleRequest& req, SimpleResponse& res) {
        appendLog("收到get /api/login 请求");
        appendLog(QString::fromStdString(req.body));
        res.status = HttpStatusCode::OK_200;
        res.body = R"({"Name": "Hello, World!", "Pwd":"123456"})";
    });
    m_httpServer->postJsonApi("/api/login", [&](const SimpleRequest& req, SimpleResponse& res) {
        appendLog("收到post /api/login 请求");
        appendLog(QString::fromStdString(req.body));
        res.status = HttpStatusCode::OK_200;
        res.body = R"({"Name": "Hello, World!", "Pwd":"123456"})";
    });
    if (m_httpServer->listen(8080)) {
        appendLog("HTTP Server is running on port 8080...");
    }
    else {
        appendLog("Failed to start server!");
        return;
    }

}

/// <summary>
/// TCP通信模块自定义 服务端
/// </summary>
void QtCommonComponet::initTCPServer()
{
    connect(&m_server, &QTcpServer::newConnection, this, &QtCommonComponet::slot_newConnection);
    if (!m_server.listen(QHostAddress::Any, 8081)) {
        qDebug() << "TCP 启动失败";
    }
}
void QtCommonComponet::stopServer()
{
    if (m_server.isListening())
    {
        for (auto socket : m_clientSockets)
        {
            bool signal = socket->blockSignals(true);
            socket->close();
            socket->blockSignals(signal);
        }
    }

    m_clientSockets.clear();
    m_server.close();
}
void QtCommonComponet::slot_newConnection() {
    QTcpSocket* clientSocket = m_server.nextPendingConnection();
    if (clientSocket == nullptr)
        return;

    m_clientSockets.insert(clientSocket);

    connect(clientSocket, &QTcpSocket::readyRead, this, &QtCommonComponet::slot_reciveData);
    connect(clientSocket, &QTcpSocket::disconnected, this, &QtCommonComponet::slot_disconnected);
}
void QtCommonComponet::slot_disconnected() {
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
    if (socket)
    {
        m_clientSockets.remove(socket);
        socket->deleteLater();
    }
}
void QtCommonComponet::slot_reciveData()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());

    bool unpackSuccess = false;
    if (socket->bytesAvailable()) {
        QByteArray data = m_clientSocket->readAll();
        /*QByteArray unpacked = CustomProtocol::unpackData(data, unpackSuccess);

        if (unpackSuccess) {
            QString text = QString::fromUtf8(unpacked);
            qDebug() << "Received text:" << text;

        }
        else {
            qDebug() << "Protocol unpack failed! Raw data:" << unpacked.toHex();
        }*/

        QByteArray resp = "success";

        socket->write(resp);
        socket->flush();
    }
}
/// <summary>
/// tcp客户端自定义
/// </summary>
void QtCommonComponet::initTCPClient()
{
    m_clientSocket = new QTcpSocket(this);
    connect(m_clientSocket, &QTcpSocket::connected, this, &QtCommonComponet::slot_newConnection);

    m_clientSocket->connectToHost("127.0.0.1", 8081);
}
void QtCommonComponet::slot_newConnectionClient()
{
    connect(m_clientSocket, &QTcpSocket::readyRead, this, &QtCommonComponet::slot_getDataFromServer);
    connect(m_clientSocket, &QTcpSocket::disconnected, this, &QtCommonComponet::slot_disconnected);
}
void QtCommonComponet::slot_getDataFromServer()
{
    if (m_clientSocket->bytesAvailable()) {
        QByteArray data = m_clientSocket->readAll();
        static QByteArray buffer;
        buffer.append(data);

        while (buffer.contains('#')) {
            int startIdx = buffer.indexOf('#');
            int endIdx = buffer.indexOf('#', startIdx + 1);

            if (startIdx != -1 && endIdx != -1) {
                QByteArray message = buffer.mid(startIdx, endIdx - startIdx + 1);
                QString messageStr = QString::fromUtf8(message);
                qDebug() << "收到数据:" << messageStr;
                buffer.remove(0, endIdx + 1);
            }
            else {
                break;
            }
        }
    }
}
void QtCommonComponet::slot_disconnectedClient()
{
    qDebug() << "未与TCPserver连接";
}
void QtCommonComponet::slot_sendData()
{
    QString data = "# message #";


    if (m_clientSocket->state() == QAbstractSocket::ConnectedState) {
        m_clientSocket->write(data.toUtf8());
        m_clientSocket->flush();
    }
}


/// <summary>
/// 串口通信模块使用
/// </summary>
void QtCommonComponet::initComSerialPort()
{
    QList<QSerialPortInfo> serialPortInfo = QSerialPortInfo::availablePorts();
    ui->comboBox_SerialPortItems->clear();
    ui->comboBox_SerialPortItems->addItem(NULL);
    ui->comboBox_SerialPortItems->blockSignals(true);

    foreach(auto port_item, serialPortInfo) {
        QString portName = port_item.portName();
        QString port_describe = port_item.description();
        QString show_name_des = QString("%1 (%2)").arg(portName).arg(port_describe);

        ui->comboBox_SerialPortItems->addItem(show_name_des, portName);

        if (portName == m_scan_com_name) {
            ui->comboBox_SerialPortItems->setCurrentText(show_name_des);
        }
    }
    ui->comboBox_SerialPortItems->blockSignals(false);

    m_pComDevice = new CommonComponet::ComDeviceControl(this);
    connect(m_pComDevice, &CommonComponet::ComDeviceControl::sig_connection_state, this, &QtCommonComponet::slot_connStateChange, Qt::QueuedConnection);
    connect(m_pComDevice, &CommonComponet::ComDeviceControl::sig_receiveDataFromServer, this, &QtCommonComponet::slot_reciveSerialPortData);
    m_pComDevice->Start(m_scan_com_name, "T", CommonComponet::ASYNC, 9600);
}
void QtCommonComponet::appendLog(const QString& logMessage)
{
    if (logMessage.isEmpty()) return;

    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString dateTime = currentDateTime.toString("[yyyy-MM-dd hh:mm:ss]");
    QString formatMessage = QString("<font color='gray' size='2'>%1</font>").arg(dateTime) + QString("<font color='blue'>%1</font>").arg(logMessage.trimmed());
    ui->textBrowser->append(formatMessage);

    qDebug() << logMessage;
}
void QtCommonComponet::slot_connStateChange(int state)
{
    if (state == CommonComponet::DeviceConnState::ConnectedState)
        ui->label_comSerialPort->setStyleSheet(CONTROL_LAMP_OK);
    else
        ui->label_comSerialPort->setStyleSheet(CONTROL_LAMP_NG);
}
void QtCommonComponet::slot_reciveSerialPortData(const QString& data)
{
    ui->lineEdit_serialPortData->setText(data);
}
void QtCommonComponet::slot_comportIndexChanged(int index)
{
    if (!m_pComDevice) return;

    QVariant data_item = ui->comboBox_SerialPortItems->itemData(index);
    QString comport = data_item.toString();

    m_scan_com_name = comport;
    m_pComDevice->reconnect(comport);
}


/// <summary>
/// 提示框使用
/// </summary>
void QtCommonComponet::slot_showMessageBox()
{
    messageTipShow("提示信息");
}
void QtCommonComponet::messageTipShow(const QString& msg)
{
    DialogTip tip(this, msg, 3);
    tip.exec();
}

/// <summary>
/// 多线程使用的框架
/// 记得在析构函数中调用xxManager::globalInstance().shutdown();
/// </summary>
void QtCommonComponet::initMultiThreadFramework()
{
    xxManager& manager = xxManager::globalInstance();
}

/// <summary>
/// 提示音播放 Qt6不支持
/// </summary>
void QtCommonComponet::slot_soundPlay()
{
    m_bell = new QSound(":/resource/skype.wav", this);  // 指定父对象自动管理内存
    m_bell->play();
}

/// <summary>
/// 打印机
/// </summary>
void QtCommonComponet::slot_printTag()
{
    m_print_device = ui->comboBox_printInfo->currentText().trimmed();
    if (!m_pTagPrintControl)
    {
        appendLog("打印标签未正确初始化");
        return;
    }

    QString appPath = QCoreApplication::applicationDirPath();
    QString print_contentPath = appPath + QDir::separator() + "config/tag.prn";

    QFile file(print_contentPath);
    if (file.exists())
    {
        file.open(QFile::ReadOnly | QFile::Text);
        QTextCodec* codec = QTextCodec::codecForName("UTF8");
        m_printContent = codec->toUnicode(file.readAll());
    }

    if (m_printContent.isEmpty())
    {
        appendLog("标签打印模板内容未空,请检查");
        return ;
    }

    m_pTagPrintControl->SendContentPrint(m_print_device, m_printContent);
    messageTipShow("打印成功");
}
